package com.atguigu.gmall.index.config;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Configuration
public class BloomFilterCongifg {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private GmallPmsClient gmallPmsClient;

    private final static String KEY_PREFIX = "index:cates:";

    @Bean
    public RBloomFilter<String> bloomFilter() {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("index:bf");
        //初始化  长度   误判率
        bloomFilter.tryInit(2000L, 0.03);
        //给布隆过滤器初始化书库
        ResponseVo<List<CategoryEntity>> listResponseVo = gmallPmsClient.queryCategoriesById(0L);
        List<CategoryEntity> categoryEntities = listResponseVo.getData();
        if (!CollectionUtils.isEmpty(categoryEntities)) {
            categoryEntities.forEach(categoryEntity -> {
                bloomFilter.add(KEY_PREFIX + categoryEntity.getId());
            });
        }

        //todo  广告的数据也要放入布隆过滤器

        return bloomFilter;
    }
}
